#include "net.h"
//线程并发服务器
//服务器

void* handle(void* agr)
{
	int newfd = *(int*)agr;

	//5.读写
	int ret;
	char buf[BUFSI];
	while(1)
	{
		bzero(buf, BUFSI);	//清空流
		do
		{
			ret = read(newfd, buf, BUFSI);
		}while(ret < 0 && errno == EINTR);
		
		if(ret < 0)
		{
			perror("ret");
			exit(1);	
		}
		
		if(ret == 0)
		{
			break;		//客户端关闭了
		}
		//打印读到的文件
		printf("read: %s", buf);

		if(!strncasecmp(buf, QUIT, sizeof(BUFSI)))
		{
			printf("client请求退出\n");
			break;
		}

	}
	close(newfd);

}


//===============================================

int main()
{

	int fd = -1;
	struct sockaddr_in soc;
	pthread_t tid;
	
	//1.创建套接字
	fd = socket(AF_INET, SOCK_STREAM, 0);
	if(fd < 0)
	{
		perror("socket");
		exit(1);
	}

	/*优化4： 允许绑定地址快速重用 */
	int b_reuse = 1;
	setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &b_reuse, sizeof (int));

	//绑定
	soc.sin_family = AF_INET;
	soc.sin_port = htons(POTR);
#if 1
	soc.sin_addr.s_addr = htonl(INADDR_ANY);
#else 
	if(inet_ptno(AF_INET, IP_ADDR, (void*)&soc.sin_addr) != 1)
	{
		perror("inet_ptno");
		exit(1);
	}

#endif

	//2.bind
	if(bind(fd, (struct sockaddr *)&soc, sizeof(soc)) < 0)
	{
		perror("bind");
		exit(1);
	}

	//3.把主动变为被动
	if(listen(fd, BACKLOG) < 0)
	{
		perror("listen");
		exit(0);
	}
	printf ("Server starting....OK!\n");


	struct sockaddr_in sin;
	socklen_t socklen = sizeof(sin);
	int newfd;
	while(1)
	{
		//4.等待客户端连接
		if(newfd = accept(fd, (struct sockaddr *)&sin, &socklen) < 0)
		{
			perror("accept");
			exit(1);
		}
		char addr[16];
		//获取连接客户端端口和ip
		if(!inet_ntop(AF_INET, (void*)&sin.sin_addr, addr, sizeof(sin)))
		{
			perror("inet_ntop");
			exit(1);
		}
		printf("client ip: %s ip: %d",addr, htons(sin.sin_port));

		//线程处理
		pthread_create(&tid, NULL, handle, (void* )&newfd);

	}

	//关闭文件
	close(fd);
	return 0;
}


























